<?php
/**
 * GioCMS
 * 
 * LICENSE
 *
 * This source file is subject to the GNU GENERAL PUBLIC LICENSE Version 2 
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.gnu.org/licenses/gpl-2.0.txt
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@ninhgio.com so we can send you a copy immediately.
 * 
 * @copyright	Copyright (c) 2010-2011 GioCMS (http://cms.ninhgio.com)
 * @license		http://www.gnu.org/licenses/gpl-2.0.txt GNU GENERAL PUBLIC LICENSE Version 2
 * @author		NinhGio - ninhgio@gmail.com
 * @since		1.0
 */

class Modules_Tag_Controllers_Tag extends Gio_Core_Controller
{
	/* ############################# Frontend ############################### */
	
	
	/* ############################# Backend ################################ */
	
	public function addAction()
	{
		$request = $this->getRequest();
		
		if ($request->isPost()) {
			$type = strtolower($request->getPost('type'));
			switch ($type) {
				case 'ajax':
					$this->disableLayout();
					$this->setNoRender();
					$tagText = trim($request->getPost('tag_text'));
					$tagText = $this->view->STRING->escape($tagText);
					//$tagText = Gio_Core_String::stripTags($tagText, array('.'));
					$response = array(
						'status' => 'RESULT_NOT_OK',
						'tag_text'	=> null,
						'tag_id'	=> null,
					);
					$json = new Services_JSON();
					
					if ($tagText) {
						if (Modules_Tag_Services_Tag::checkExist($tagText)) {
							$response['status'] = 'RESULT_EXIST';		
						} else {
							$tag = array(
								'tag_text'		=> $tagText,
								'slug'			=> Gio_Core_String::removeSign($tagText, '-', true),
								'created_date'	=> date('Y-m-d H:i:s')
							);
							$tagId = Modules_Tag_Services_Tag::add($tag);
							$response['status'] = 'RESULT_OK';
							$response['tag_text'] = $tagText;
							$response['tag_id'] = $tagId;
						}
					}
					
					$this->getResponse()->setBody($json->encodeUnsafe($response));
					return;					
					break;
				default:
					$tagData = $request->getPost('tag');
					$tagData = Modules_Tag_Services_Tag::validate($tagData);
					
					if (isset($tagData['messages_error']) && $tagData['messages_error']) {
						$this->view->errorMessages = $tagData['messages'];
						$this->view->tagData = $tagData;
						return;
					}
					
					if (Modules_Tag_Services_Tag::checkExist($tagData['tag_text'])) {
						$this->view->tagData = $tagData;
						$this->view->existMessage = true;
						return;
					}
					
					$tag = array(
							'tag_text' 	=> $this->view->STRING->escape($tagData['tag_text']),
							'slug'  	=> $tagData['slug'],
							'created_date'	=> date('Y-m-d H:i:s'),
					);
					$tagId = Modules_Tag_Services_Tag::add($tag);
					Gio_Core_Messenger::getInstance()
										->addMessage($this->view->TRANSLATOR->translator('tag_actions_add_success'));
					$this->redirect($this->view->url('tag_tag_add'));
					break;
			}			
		}
	}
	
	public function deleteAction()
	{
		$this->disableLayout();
		$this->setNoRender();
		
		$request = $this->getRequest();
		if (!$request->isPost()) {
			return;
		}
		$id = $request->getPost('tag_id');
		$tag = Modules_Tag_Services_Tag::getById($id);
		
		$condition = array('tag_id' => $id);
		if (null == $tag || Modules_Tag_Services_TagItem::count($condition) > 0){
			$this->getResponse()->setBody('RESULT_NOT_OK');
			return;	
		}
		
		Modules_Tag_Services_Tag::delete($id);
		$this->getResponse()->setBody('RESULT_OK');
	}
	
	public function editAction()
	{
		$request = $this->getRequest();
		
		$tagId = $request->getParam('tag_id');
		$tag = Modules_Tag_Services_Tag::getById($tagId);
		if (null == $tag) {
			Modules_Core_Services_Exception::error('DATA_NOT_FOUND');
		}
		
		$this->view->tagData = $tag;
		
		if ($request->isPost()) {
			$tagData = $request->getPost('tag');
			$tagData = Modules_Tag_Services_Tag::validate($tagData);
			
			if (isset($tagData['messages_error']) && $tagData['messages_error']) {
				$this->view->errorMessages = $tagData['messages'];
				$this->view->tagData = $tagData;
				return;
			}
			
			if (Modules_Tag_Services_Tag::checkExist($tagData['tag_text'], $tag['tag_id'])) {
				$this->view->tagData = $tagData;
				$this->view->existMessage = true;
				return;
			}
			
			$tag['tag_text'] = $tagData['tag_text'];
			$tag['slug'] 	 = $tagData['slug'];
			
			Modules_Tag_Services_Tag::update($tag);
			Gio_Core_Messenger::getInstance()
								->addMessage($this->view->TRANSLATOR->translator('tag_actions_edit_success'));
			$this->redirect($this->view->url('tag_tag_edit', $tag));
		}
	}
	
	public function listAction()
	{
		$request = $this->getRequest();
		$lang    = $request->getParam('lang');
		$this->view->lang = $lang;
		$paramLang = ($lang) ? '/' . $lang : null;
		
		$perPage = 20;
		$pageIndex = (int)$request->getParam('page_index');
		if (null == $pageIndex || '' == $pageIndex || $pageIndex < 0) {
			$pageIndex = 1;
		}
		$start = ($pageIndex - 1) * $perPage;
		$this->view->pageIndex = $pageIndex;
		
		$condition = array();
		$tags = Modules_Tag_Services_Tag::find($start, $perPage, $condition);
		$numTags = Modules_Tag_Services_Tag::count($condition);
		
		$this->view->tags = $tags; 
		
		// Pager
		require_once LIB_DIR . DS . 'PEAR' . DS . 'Pager' . DS . 'Sliding.php';
		$pagerPath = $this->view->url('tag_tag_list');
		$pagerOptions = array(
			'mode'       	=> 'Sliding',
			'append'   		=> false,
    		'perPage'    	=> $perPage,
    		'delta'      	=> 3,
			'urlVar'		=> 'page',
			'path'			=> $pagerPath,
			'fileName'		=> 'page-%d',
			'separator'		=> '',
			'nextImg' 		=> '<small class="icon arrow_right"></small>',
			'prevImg'		=> '<small class="icon arrow_left"></small>',
			'altNext'		=> '',
			'altPrev'		=> '',
			'altPage'		=> '',
    		'totalItems' 	=> $numTags,
			'currentPage'	=> $pageIndex,
			'urlSeparator'	=> '/',
			'spacesBeforeSeparator' => 0,
			'spacesAfterSeparator' => 0,
			'curPageSpanPre' => '<a href="javascript: void();" class="current">',
			'curPageSpanPost' => '</a>'
		
		);
		$pager = new Pager_Sliding($pagerOptions);
		$this->view->pager = $pager;
	}
	
	/**
	 * Tag Suggest Action
	 */
	public function suggestAction()
	{
		$this->setNoRender();
		$this->disableLayout();
		
		$request = $this->getRequest();
		$q 		 = $request->getParam('q');
		$limit 	 = $request->getParam('limit', 10);
		$limit   = ((int)$limit) ? $limit : 10;
		
		if (null == $q) {
			return;
		}
		
		$condition = array('tag_text' => $q);
		$tags    = Modules_Tag_Services_Tag::find(0, $limit, $condition);
		$return  = '';
		foreach ($tags as $tag) {
			$return .= $tag['tag_text'] . '|' . $tag['tag_id'] . "\n";
		}
		
		$this->getResponse()->setBody($return); 
	} 
}